package com.block.datapush.service.apipush;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.LogFactory;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.RongYiHuiUtil;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 城市回调 融易汇
 */
@Service
public class RongYiHui2PushApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMemberCommonService memberCommonService;

    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();
        String mobileMd5 = memberSourceInfo.getMobileMd5();

        long timestamp = System.currentTimeMillis() / 1000;

        Map<String, String> bizMap = new HashMap<>();
        bizMap.put("telephone", mobileMd5);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("app", pushApiKeyParam.getApiCode());
        paramMap.put("label", "checkUserExist");
        paramMap.put("timestamp", timestamp);
        paramMap.put("nonce", RandomUtil.randomString(32));
        paramMap.put("data", JSON.toJSONString(bizMap));

        String signature = getSign(pushApiKeyParam.getApiSecret(), paramMap);

        paramMap.put("signature", signature);


        log.info("【融易汇】撞库开始【queryUrl】{}【paramMap】{}", queryUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/x-www-form-urlencoded")
                .form(paramMap)
                .execute().body();
        log.info("【融易汇】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String message = resultObject.getString("message");
        JSONObject data = resultObject.getJSONObject("result");
        String msg = data.getString("msg");

        pushApiResult.setCode(code + "|" +message);
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "200")) {
            Boolean status = data.getBoolean("status");
            if (ObjectUtil.equal(status, true)) {
                pushApiResult.setPushSuccess(true);
            }
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        return null;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        String requestUrl = pushApiKeyParam.getRegisterUrl();

        long timestamp = System.currentTimeMillis() / 1000;

        Map<String, String> bizMap = new HashMap<>();
        bizMap.put("channel", pushApiKeyParam.getApiKey());
        bizMap.put("telephone", memberSourceInfo.getMobile());
        bizMap.put("city", memberSourceInfo.getCityCode());
        bizMap.put("city_name", memberSourceInfo.getCity());
        bizMap.put("professional", "上班族");
        bizMap.put("name", memberSourceInfo.getRealname());
        bizMap.put("idcard", memberSourceInfo.getIdcard());
        bizMap.put("SF_GZFFXS", "银行卡");
        bizMap.put("SF_DQDWGL", "12个月以上");
        bizMap.put("SF_YWYYZZ", "无营业执照");
        bizMap.put("XQ_JDS", RongYiHuiUtil.getLoanAmount(memberSourceInfo.getLoanAmount()));
        bizMap.put("XQ_JDJ", "12个月");
        bizMap.put("GR_WHCD", RongYiHuiUtil.getXueli(memberSourceInfo.getXueli()));
        bizMap.put("ZC_BDSB", RongYiHuiUtil.getSheBao(memberSourceInfo.getShebao()));
        bizMap.put("ZC_BDGJJ", RongYiHuiUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("ZC_MXFC", RongYiHuiUtil.getHouse(memberSourceInfo.getCar()));
        bizMap.put("ZC_MXCC", RongYiHuiUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("ZC_GRBX", RongYiHuiUtil.getInsurance(memberSourceInfo.getBaoxian()));
        bizMap.put("XY_ZMF", RongYiHuiUtil.getZhima(memberSourceInfo.getZhima()));
        bizMap.put("XY_WLDED", "无");
        bizMap.put("XY_YWXYK", "1万及以下");
        bizMap.put("XY_XYJL", RongYiHuiUtil.getYuqi(memberSourceInfo.getYuqi()));
        bizMap.put("XY_JDBT", RongYiHuiUtil.getJd(memberSourceInfo.getBaitiao()));
        bizMap.put("XY_HB", RongYiHuiUtil.getHuabei(memberSourceInfo.getHuabei()));


        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("app", pushApiKeyParam.getApiCode());
        paramMap.put("label", "submitCustomerData");
        paramMap.put("timestamp", timestamp);
        paramMap.put("nonce", "crm");
        paramMap.put("data", JSON.toJSONString(bizMap));

        String signature = getSign(pushApiKeyParam.getApiSecret(), paramMap);

        paramMap.put("signature", signature);

        log.info("【融易汇】导单开始【requestUrl】{}【paramMap】{}", requestUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/x-www-form-urlencoded")
                .form(paramMap)
                .execute().body();
        log.info("【融易汇】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String message = resultObject.getString("message");
        JSONObject result1 = resultObject.getJSONObject("result");
        String msg = result1.getString("msg");
        Boolean status = result1.getBoolean("status");

        pushApiResult.setCode(code + "|" +message);
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "200")) {
            if (ObjectUtil.equal(status, true)) {
                String order = result1.getString("order");
                pushApiResult.setOutOrderNo(order);
                pushApiResult.setPushSuccess(true);
                pushApiResult.setSettleFlag(false);
                pushApiResult.setStatus(PushStatusEnum.WAIT_QUERY.getValue());
            }
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());

        long timestamp = System.currentTimeMillis() / 1000;

        String requestUrl = pushApiKeyParam.getQueryUrl();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("channel", pushApiKeyParam.getApiKey());
        bizMap.put("order",pushQueryParam.getOutOrderNo()); //  订单

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("app", pushApiKeyParam.getApiCode());
        paramMap.put("label", "orderQuery");
        paramMap.put("timestamp", timestamp);
        paramMap.put("nonce", "ryh");
        paramMap.put("data", JSON.toJSONString(bizMap));

        String signature = getSign(pushApiKeyParam.getApiSecret(), paramMap);

        paramMap.put("signature", signature);


        log.info("【融易汇】查询开始【requestUrl】{}【paramMap】{}【bizMap】{}", requestUrl, JSON.toJSONString(paramMap), JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/x-www-form-urlencoded")
                .form(paramMap)
                .execute().body();
        log.info("【融易汇】查询结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String message = resultObject.getString("message");
        JSONObject result1 = resultObject.getJSONObject("result");
        String msg = result1.getString("msg");
        Boolean status = result1.getBoolean("status");

        pushApiResult.setCode(code + "|" +message);
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "200")) {
            if (ObjectUtil.equal(status, true)) {
                pushApiResult.setPushSuccess(true);
                pushApiResult.setSettleFlag(true);
                pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
                return pushApiResult;
            }
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    private static String getSign(String apiToken, Map<String, Object> bizMap) {
        List<String> valueList = new ArrayList<>();

        for (Object value : bizMap.values()) {
            valueList.add(String.valueOf(value));
        }
        valueList.add(apiToken);

        Collections.sort(valueList, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                String namea = o1.toUpperCase();
                String nameb = o2.toUpperCase();
                return StrUtil.compare(namea, nameb, true);
            }
        });

        StringBuilder stringBuilder = new StringBuilder();
        for (String value : valueList) {
            stringBuilder.append(value);
        }
        System.out.println(stringBuilder.toString());
        return SecureUtil.sha1(stringBuilder.toString());
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }


    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        return null;
    }
}
